<script setup lang="ts">
import { ref, onMounted, nextTick } from 'vue';
import { ElMessage } from 'element-plus';
import * as echarts from 'echarts';
import type { DorisStorage } from '@/service/api/dataplatform/doris-storage';
import { getDorisStorageList } from '@/service/api/dataplatform/doris-storage';

const visible = ref(false);
const loading = ref(false);
const chartRef = ref<HTMLDivElement>();
let chartInstance: echarts.ECharts | null = null;

const storageList = ref<DorisStorage[]>([]);

/** 打开弹窗 */
async function open() {
  visible.value = true;
  await loadStorageData();
  await nextTick();
  initChart();
}

/** 加载存储数据 */
async function loadStorageData() {
  try {
    loading.value = true;
    const { data } = await getDorisStorageList({ pageNum: 1, pageSize: 100 });
    storageList.value = data?.rows || [];
  } catch (error) {
    console.error('加载存储数据失败:', error);
    ElMessage.error('加载存储数据失败');
  } finally {
    loading.value = false;
  }
}

/** 初始化图表 */
function initChart() {
  if (!chartRef.value) return;
  
  if (chartInstance) {
    chartInstance.dispose();
  }
  
  chartInstance = echarts.init(chartRef.value);
  
  // 按数据库分组统计
  const dbStats = new Map<string, { tableCount: number; totalSize: number }>();
  
  storageList.value.forEach(item => {
    const dbName = item.databaseName || 'unknown';
    const stats = dbStats.get(dbName) || { tableCount: 0, totalSize: 0 };
    stats.tableCount++;
    stats.totalSize += item.dataSize || 0;
    dbStats.set(dbName, stats);
  });
  
  const databases = Array.from(dbStats.keys());
  const tableCounts = databases.map(db => dbStats.get(db)!.tableCount);
  const dataSizes = databases.map(db => {
    const sizeInGB = (dbStats.get(db)!.totalSize / (1024 * 1024 * 1024)).toFixed(2);
    return parseFloat(sizeInGB);
  });
  
  const option: echarts.EChartsOption = {
    title: {
      text: '数据库存储统计',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross',
        crossStyle: {
          color: '#999'
        }
      }
    },
    legend: {
      data: ['表数量', '数据大小(GB)'],
      top: 30
    },
    xAxis: [
      {
        type: 'category',
        data: databases,
        axisPointer: {
          type: 'shadow'
        },
        axisLabel: {
          rotate: 45,
          interval: 0
        }
      }
    ],
    yAxis: [
      {
        type: 'value',
        name: '表数量',
        min: 0,
        axisLabel: {
          formatter: '{value}'
        }
      },
      {
        type: 'value',
        name: '数据大小(GB)',
        min: 0,
        axisLabel: {
          formatter: '{value} GB'
        }
      }
    ],
    series: [
      {
        name: '表数量',
        type: 'bar',
        data: tableCounts,
        itemStyle: {
          color: '#5470c6'
        }
      },
      {
        name: '数据大小(GB)',
        type: 'line',
        yAxisIndex: 1,
        data: dataSizes,
        itemStyle: {
          color: '#91cc75'
        }
      }
    ],
    grid: {
      bottom: 80
    }
  };
  
  chartInstance.setOption(option);
}

/** 关闭弹窗 */
function handleClose() {
  if (chartInstance) {
    chartInstance.dispose();
    chartInstance = null;
  }
}

defineExpose({
  open
});
</script>

<template>
  <el-dialog
    v-model="visible"
    title="存储空间统计"
    width="80%"
    destroy-on-close
    @close="handleClose"
  >
    <div v-loading="loading" class="statistics-container">
      <!-- 总体统计 -->
      <el-row :gutter="16" class="summary-row">
        <el-col :span="6">
          <el-card shadow="hover">
            <el-statistic title="数据库总数" :value="new Set(storageList.map(s => s.databaseName)).size" />
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover">
            <el-statistic title="表总数" :value="storageList.length" />
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover">
            <el-statistic
              title="总行数"
              :value="storageList.reduce((sum, s) => sum + (s.rowCount || 0), 0)"
              :precision="0"
            />
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover">
            <el-statistic
              title="总数据大小"
              :value="(storageList.reduce((sum, s) => sum + (s.dataSize || 0), 0) / (1024 * 1024 * 1024)).toFixed(2)"
              suffix="GB"
            />
          </el-card>
        </el-col>
      </el-row>

      <!-- 图表 -->
      <div ref="chartRef" class="chart-container" />

      <!-- 表格 -->
      <el-table
        :data="storageList"
        border
        stripe
        style="width: 100%; margin-top: 20px"
        max-height="400"
      >
        <el-table-column prop="databaseName" label="数据库" width="150" />
        <el-table-column prop="tableName" label="表名" width="200" />
        <el-table-column prop="tableType" label="表类型" width="120" />
        <el-table-column label="行数" width="150">
          <template #default="scope">
            {{ scope && scope.row ? (scope.row.rowCount?.toLocaleString() || 0) : 0 }}
          </template>
        </el-table-column>
        <el-table-column label="数据大小" width="150">
          <template #default="scope">
            {{ scope && scope.row ? (((scope.row.dataSize || 0) / (1024 * 1024)).toFixed(2) + ' MB') : '0 MB' }}
          </template>
        </el-table-column>
        <el-table-column prop="partitionCount" label="分区数" width="100" />
        <el-table-column prop="tableComment" label="注释" show-overflow-tooltip />
      </el-table>
    </div>
  </el-dialog>
</template>

<style scoped lang="scss">
.statistics-container {
  .summary-row {
    margin-bottom: 20px;
  }

  .chart-container {
    width: 100%;
    height: 400px;
  }
}
</style>
